<template>
  <el-card>
    <el-steps :space="200" :active="activeIndex - 0" finish-status="success">
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
    </el-steps>
    <el-form
      :model="addForm"
      :rules="addRules"
      ref="addrFormRef"
      label-width="100px"
      label-position="top"
    >
      <el-tabs
        v-model="activeIndex"
        :tab-position="'left'"
        @tab-click="handleClick"
        :before-leave="tabsChange"
      >
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addForm.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="addForm.goods_weight" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="addForm.goods_number" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              v-model="addForm.goods_cat"
              :options="cateList"
              :props="casValue"
              clearable
              @change="casChange"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form-item
            v-for="item in paramsList"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <!-- <div>{{ item }}</div> -->
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                v-for="(item1, i) in item.attr_vals"
                :key="i"
                :label="item1"
                border
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form-item
            v-for="item in onlyData"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headersObj"
            :on-success="picSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="50%"
            @close="closePreview"
          >
            <img :src="previewPicUrl" style="width: 100%" alt="" />
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <!-- 富文本编辑器组件 -->
          <quill-editor
            v-model="addForm.goods_introduce"
            :options="editorOption"
          ></quill-editor>
          <el-button type="primary" style="margin-top: 10px" @click="addGoods"
            >添加商品</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </el-card>
</template>

<script>
const _ = require('lodash')
export default {
  data() {
    return {
      // 富文本编辑器
      editorOption: {},
      activeIndex: 0,
      addForm: {
        goods_name: '1',
        goods_price: '2',
        goods_weight: '3',
        goods_number: '4',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      paramsList: [],
      onlyData: [],
      cateList: [],
      casValue: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      addRules: {
        goods_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        goods_price: [{ required: true, message: '不能为空', trigger: 'blur' }],
        goods_weight: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_cat: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      // 为上传图片通过headers设置请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 上传图片地址
      uploadUrl: 'https://www.liulongbin.top:8888/api/private/v1/upload',
      // 预览图片
      dialogVisible: false,
      previewPicUrl: ''
    }
  },
  watch: {
    // 'addForm.goods_cat'(val) {
    //   if (val.length !== 3) {
    //     this.$message.warning('只允许选择三级分类')
    //     this.addForm.goods_cat = [] // (报错) 不要在监听的时候改变所监听的数据
    //   }
    // }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    addGoods() {
      // console.log(this.addForm)
      this.$refs.addrFormRef.validate((valid) => {
        if (!valid) {
          return this.$message.error('请输入必填信息')
        }
        // 将 goods_cat 变成以','分割的字符串
        // 方法一 (重新赋值后可能会报错, 因为级联选择器的goods_cat为数组)
        // 1.JSON.parse(JSON.stringify(value)) 将值深拷贝
        // 2.使用 join(',) 方法将数组转换成字符串
        // 3.重新复制
        // const saveObj = JSON.parse(JSON.stringify(this.addForm.goods_cat))
        // const obj = saveObj.join(',')
        // this.addForm.goods_cat = obj

        // 方法二 使用 lodash 插件的 _.cloneDeep 方法实现深拷贝
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')

        // 处理商品参数
        this.paramsList.forEach((item) => {
          const paramsObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(paramsObj)
        })
        // 处理商品属性
        this.onlyData.forEach((item) => {
          const onlyObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(onlyObj)
        })

        form.attrs = this.addForm.attrs
        // console.log(form)
        this.$http.post('goods', form).then((res) => {
          console.log(res)
        })
      })
    },
    tabsChange(activeName, oldActiveName) {
      // console.log('即将离开:' + oldActiveName)
      // console.log('即将进入:' + activeName)
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择三级分类')
        return false
      }
      if (activeName === '1') {
        this.$http
          .get(`categories/${this.cateId}/attributes`, {
            params: { sel: 'many' }
          })
          .then((res) => {
            res.data.data.forEach((item) => {
              // console.log(item)
              // console.log(item.attr_vals.length)
              item.attr_vals =
                item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
            })
            this.paramsList = res.data.data
          })
      } else if (activeName === '2') {
        this.$http
          .get(`categories/${this.cateId}/attributes`, {
            params: {
              sel: 'only'
            }
          })
          .then((res) => {
            this.onlyData = res.data.data
          })
      }
    },
    casChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.warning('只允许选择三级分类')
        this.addForm.goods_cat = []
      }
    },
    handleClick(tab) {},
    handlePreview(file) {
      this.previewPicUrl = file.response.data.url
      this.dialogVisible = true
    },
    closePreview() {
      this.dialogVisible = false
    },
    // 删除图片
    handleRemove(file) {
      // 1.获取删除图片的临时路径
      const tPath = file.response.data.tmp_path
      // 2.从pics数组中,找到这个图片对应的索引值
      const i = this.addForm.pics.findIndex((v) => v.picsPath === tPath)
      // 3.调用数组的splice方法,把图片信息对象从pics数组中移除
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    getGoodsList() {
      this.$http.get('categories').then((res) => {
        this.cateList = res.data.data
      })
    },
    picSuccess(response) {
      // 1.拼接得到一个图片的信息对象
      const tempPath = {
        picsPath: response.data.tmp_path
      }
      // 2.将图片信息对象push到pic数组中
      this.addForm.pics.push(tempPath)
      console.log(this.addForm)
    }
  }
}
</script>

<style>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.ql-editor {
  min-height: 200px;
}
</style>
